package com.cytech.cloudclinic.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cytech.cloudclinic.R;
import com.cytech.cloudclinic.adapter.AddDrugTagAdapter;
import com.cytech.cloudclinic.base.BaseBean;
import com.cytech.cloudclinic.base.BaseObserver;
import com.cytech.cloudclinic.bean.AddDrugTag;
import com.cytech.cloudclinic.bean.Drug;
import com.cytech.cloudclinic.bean.DrugTag;
import com.cytech.cloudclinic.bean.event.UpdateAddTagEvent;
import com.cytech.cloudclinic.utils.ConvertUtils;
import com.cytech.cloudclinic.utils.RequestWithViewUtils;
import com.yechaoa.yutils.YUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.cytech.cloudclinic.app.Constant.MODE_ACUPOINT_TIME;

/**
 * 修改敷贴时间对话框
 */
public class EditDrugTimeDialog extends DialogFragment {
    @BindView(R.id.diglog_drug_time_rv)
    RecyclerView timeRv;
    @BindView(R.id.diglog_drug_number_rv)
    RecyclerView numberRv;

    @BindView(R.id.dialog_tv_drug_name)
    TextView drugName;
    @BindView(R.id.tv_prescription_time)
    TextView timeTv;
    @BindView(R.id.tv_prescription_number)
    TextView numberTv;

    private List<AddDrugTag> timeList;
    private List<AddDrugTag> numberList;
    private AddDrugTagAdapter timeAdapter;
    private AddDrugTagAdapter numberAdapter;

    private Drug drug;
    private int drugParentTagId;

    private OnSaveClickListener onSaveClickListener;


    public EditDrugTimeDialog(int drug_tag_id, Drug drug, OnSaveClickListener onSaveClickListener) {
        this.onSaveClickListener = onSaveClickListener;
        Bundle bundle = new Bundle();
        bundle.putInt("drug_tag_id",drug_tag_id);
        bundle.putSerializable("drug",drug);
        setArguments(bundle);
    }

    @Override
    public void onStart() {
        super.onStart();
        WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
        lp.width = (int) (0.9* YUtils.getScreenWidth());
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getDialog().getWindow().setAttributes(lp);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_edit_drug_time, null);
        ButterKnife.bind(this, view);
        builder.setView(view);
        initCountRv();
        initUseRv();

         drugParentTagId = getArguments().getInt("drug_tag_id");
        drug = (Drug) getArguments().getSerializable("drug");

        drugName.setText(drug.drug_name);
        getSummaryList(drugParentTagId);
        return builder.create();
    }

    //时间
    private void initCountRv() {
        timeList = new ArrayList<>();
        timeAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, timeList);
        timeRv.setLayoutManager(new GridLayoutManager(getActivity(), 6));
        timeRv.setAdapter(timeAdapter);

        timeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                AddDrugTag tag = timeAdapter.getItem(position);
                if(tag.isAddData){
                    AddDrugTagDialog addDrugTagDialog = new AddDrugTagDialog(6,drugParentTagId);
                    addDrugTagDialog.show(getChildFragmentManager(),"addTag");
                }else{
                    timeAdapter.setCurrentPos(position);
                    String value = tag.value;
                    timeTv.setText(value);
                }
            }
        });
    }


    //贴数
    private void initUseRv() {
        numberList = buildNumValue();
        numberAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, numberList);
        numberRv.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        numberRv.setAdapter(numberAdapter);

        numberAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String value = numberAdapter.getItem(position).value;
                numberTv.setText(ConvertUtils.getRealNumValue(value, numberTv.getText().toString()));
            }
        });
    }

    @OnClick(R.id.dialog_update_unit_cancel)
    public void onClickCancel(View view){
        dismiss();
    }

    @OnClick(R.id.dialog_update_unit_save)
    public void onClickSave(View view){
        dismiss();
        if(onSaveClickListener!=null){
            drug.acupoints.acupoint_time = timeTv.getText().toString();
            drug.acupoints.acupoint_number = ConvertUtils.toInt(numberTv.getText().toString());
            onSaveClickListener.onSave(drug);
        }

    }



    public void getSummaryList(int drugParentId) {
        JSONObject json = new JSONObject();
        try {
            json.put("mode_id",MODE_ACUPOINT_TIME);
            json.put("drug_id",drugParentId);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        String requestStr = json.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestStr);
        RequestWithViewUtils.getInstance().addDisposable(RequestWithViewUtils.getInstance().apiServer.getSummaryList(body), new BaseObserver<BaseBean<List<AddDrugTag>>>(null, false) {
            @Override
            public void onSuccess(BaseBean<List<AddDrugTag>> o) {
                o.result.add(new AddDrugTag(true));
                timeAdapter.setNewInstance(o.result);
            }

            @Override
            public void onError(String msg) {

            }
        });
    }


    public List<AddDrugTag> buildNumValue(){
        List<AddDrugTag> numList = new ArrayList<>();
        numList.add(new AddDrugTag("1",false));
        numList.add(new AddDrugTag("2",false));
        numList.add(new AddDrugTag("3",false));
        numList.add(new AddDrugTag("4",false));
        numList.add(new AddDrugTag("5",false));
        numList.add(new AddDrugTag("6",false));
        numList.add(new AddDrugTag("7",false));
        numList.add(new AddDrugTag("8",false));
        numList.add(new AddDrugTag("9",false));
        numList.add(new AddDrugTag("0",false));
        numList.add(new AddDrugTag(".",false));
        numList.add(new AddDrugTag("清除",false));
        return numList;
    }

    public interface OnSaveClickListener{
        void onSave(Drug drug);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateData(UpdateAddTagEvent event) {
        getSummaryList(drugParentTagId);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
